import time


class RequestTimeMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 记录请求开始时间
        start_time = time.time()

        # 处理请求
        response = self.get_response(request)

        # 计算耗时
        duration = time.time() - start_time
        print(f"[{request.method}] {request.path} 耗时: {duration:.2f}秒")
        response["X-Request-Duration"] = f"{duration:.2f}s"  # 写入响应头

        return response